package com.qdlc.p2p.biz.service.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.qdlc.p2p.biz.service.BaseGiveAwardService;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.common.util.OrderNoUtil;
import com.qdlc.p2p.dal.dao.NewActivityAwardLogDao;
import com.qdlc.p2p.dal.dao.RateInterestDao;
import com.qdlc.p2p.dal.dao.RateRuleDao;
import com.qdlc.p2p.dal.dao.RateRuleDetailDao;
import com.qdlc.p2p.dal.dto.NewActivityAwardLog;
import com.qdlc.p2p.dal.dto.RateInterest;
import com.qdlc.p2p.dal.dto.RateRule;
import com.qdlc.p2p.dal.dto.RateRuleDetail;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.model.BaseGiveAwardModel;
import com.qdlc.p2p.dal.model.RateRuleModel;

/**
 * 发放加息券
 * Created by liaoxiangkai on 2015/11/25.
 */
@Service("giveUserUpRateService")
public class GiveUserUpRateServiceImpl implements BaseGiveAwardService {
    private static Logger logger = Logger.getLogger(GiveUserUpRateServiceImpl.class);

    @Resource
    private RateRuleDao rateRuleDao;

    @Resource
    private RateRuleDetailDao rateRuleDetailDao;

    @Resource
    private RateInterestDao rateInterestDao;

    @Resource
    private NewActivityAwardLogDao newActivityAwardLogDao;

    @Override
    public void giveAward(BaseGiveAwardModel baseGiveAwardModel) {
        User user = baseGiveAwardModel.getUser();
        if (user == null || user.getUserId() < 0) {
            return;
        }
        long ruleId = baseGiveAwardModel.getRuleId();
        RateRule rateRule = rateRuleDao.find(ruleId);
        if (null == rateRule) {
            logger.info("发放加息券奖励异常，规则未找到。rateRuleId的ID：" + ruleId);
            //throw new UpRateException(MessageUtil.getMessage("MF002002007"));
            return;
        }
        Date addTime = DateUtil.getNow();
        Date endTime = DateUtil.rollDayStart(addTime, rateRule.getValitTime());
        //realPayTotal实际发放数量，payTotal发放数量
        int realPayTotal = rateRuleDao.getRealRepayTotal(rateRule.getId());
        RateRuleModel ruleModel = RateRuleModel.instance(rateRule);
        //校验加息券发放规则的有效性
        boolean falg = ruleModel.checkRateRule(addTime, realPayTotal);
        if (!falg) {
            logger.info("使用加息券规则已经过期，终止业务逻辑处理！");
            return;
        }
        double apr = rateFactory(rateRule, baseGiveAwardModel.getAmount());
        if (apr <= 0) {
            logger.info("当前发放加息券未找到合理的规则匹配，发送失败！！");
            return;
        }
        //更新该规则已经发送的加息券总数
        rateRuleDao.updateRateRule(ruleId, 1);
        //保存用户获得加息券记录
        RateInterest rateInterest = new RateInterest();
        rateInterest.setName(rateRule.getRuleName());
        rateInterest.setSourceType(baseGiveAwardModel.getSourceType());
        rateInterest.setAddTime(addTime);
        rateInterest.setInteNo(OrderNoUtil.getInstance().getSerialNumber());
        rateInterest.setRateRuleId(ruleId);
        rateInterest.setUserId(user.getUserId());
        rateInterest.setRemark(baseGiveAwardModel.getDescription());
        rateInterest.setValitDay(rateRule.getValitTime());
        rateInterest.setStatus(0);
        rateInterest.setUpApr(apr);
        rateInterest.setEndTime(endTime);
        rateInterest = rateInterestDao.save(rateInterest);
        if (rateInterest != null) {
            //赠与活动记录
            NewActivityAwardLog newActivityAwardLog = new NewActivityAwardLog();
            newActivityAwardLog.setUser(user);
            newActivityAwardLog.setTache(baseGiveAwardModel.getSourceType());
            newActivityAwardLog.setRuleType(baseGiveAwardModel.getRuleType());
            newActivityAwardLog.setRuleId(baseGiveAwardModel.getRuleId());
            newActivityAwardLog.setCount(1);
            newActivityAwardLog.setAmount(apr);
            newActivityAwardLog.setAddTime(new Date());
            newActivityAwardLogDao.save(newActivityAwardLog);
        }
    }

    //产生一个加息券实体
    public double rateFactory(RateRule rateRule, double tenderMoney) {
        int payWay = rateRule.getPayWay();
        switch (payWay) {
            case 1: //按固定值发放
                return rateRule.getUpApr();
            case 2:  //按投资额度发放
                List<RateRuleDetail> detailList = rateRuleDetailDao.getrateDetailListByRid(rateRule.getId());
                for (RateRuleDetail detail : detailList) { //循环规则详情，产生加息额度
                    if (detail.getMin() <= tenderMoney && tenderMoney < detail.getMax()) {
                        return detail.getRateApr();
                    }
                }
                return 0;
            default:
                return 0;
        }
    }

    /**
     * 发放给单个用户
     * @param baseGiveAwardModel
     */
    @Override
    public void giveSingleUserAward(BaseGiveAwardModel baseGiveAwardModel) {
        RateInterest rateInterest = new RateInterest();

        RateRule rateRule = rateRuleDao.find(baseGiveAwardModel.getRuleId());
        if (null == rateRule) {
            logger.info("发放加息券奖励异常，规则未找到。rateRuleId的ID：" + baseGiveAwardModel.getRuleId());
            return;
        }
        Date addTime = DateUtil.getNow();
        Date endTime = DateUtil.rollDayStart(addTime, rateRule.getValitTime());
        //realPayTotal实际发放数量，payTotal发放数量
        int realPayTotal = rateRuleDao.getRealRepayTotal(rateRule.getId());
        RateRuleModel ruleModel = RateRuleModel.instance(rateRule);
        //校验加息券发放规则的有效性
        boolean falg = ruleModel.checkRateRule(addTime, realPayTotal);
        if (!falg) {
            logger.info("使用加息券规则已经过期，终止业务逻辑处理！");
            return;
        }
        double apr = rateFactory(rateRule, baseGiveAwardModel.getAmount());
        if (apr <= 0) {
            logger.info("当前发放加息券未找到合理的规则匹配，发送失败！！");
            return;
        }
        //更新该规则已经发送的加息券总数
        rateRuleDao.updateRateRule(baseGiveAwardModel.getRuleId(), 1);

        rateInterest.setAddTime(addTime);
        rateInterest.setInteNo(OrderNoUtil.getInstance().getSerialNumber());
        rateInterest.setUserId(baseGiveAwardModel.getUser().getUserId());
        rateInterest.setName(baseGiveAwardModel.getDescription());
        rateInterest.setValitDay(rateRule.getValitTime());
        rateInterest.setRateRuleId(rateRule.getId());
        rateInterest.setSourceType(baseGiveAwardModel.getSourceType());
        rateInterest.setRemark(baseGiveAwardModel.getDescription());
        rateInterest.setStatus(0);
        rateInterest.setUpApr(rateRule.getUpApr());
        rateInterest.setEndTime(endTime);
        rateInterest = rateInterestDao.save(rateInterest);
        if (null != rateInterest) {
            NewActivityAwardLog newActivityAwardLog = new NewActivityAwardLog(baseGiveAwardModel.getUser(), baseGiveAwardModel.getSourceType(),rateRule.getUpApr(), BaseGiveAwardModel.RULE_TYPE_UPRATE);
            newActivityAwardLogDao.save(newActivityAwardLog);
        }
    }
}
